﻿Public Class Main
    Public Shared Function Main(ByVal args() As String) As Integer
        Try
            'System.Diagnostics.Debugger.Launch()

            Randomize(Environment.TickCount)

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
            AddHandler Application.ThreadException, AddressOf UnhandledExceptionHandler_Thread
            AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler_Domain

            Application.EnableVisualStyles()

            Dim clsMainView As FMain
            Using clsMessage As New Framework.Message("Starting Buddy 2 Buddy...")
                ReadCommandLine(args)
                ReadIsoStorageSettings()

                Framework.Settings.Provider.RegisterProvider(New FSettings.Provider)

                '' Initialize Datastore
                If Not SetupDatastore.Manager.EnsureLocalDataBaseIsUpToDate(clsMessage.Form) Then Return -1

                clsMainView = New FMain
                Framework.Threading.MainGuiForm = clsMainView
                clsMainView.Show()
                clsMainView.Enabled = False
                Application.DoEvents()

                Framework.Log.Provider.RegisterProvider(clsMainView)

                Host.Init(clsMainView)


                '' Initialize NetNode
                If Framework.Net.Settings.SetupLevel_Saved <> Framework.Net.Settings.SetupLevel_Required Then
                    Dim clsSettingsView As New FSettings
                    If Not clsSettingsView.ShowDialog(clsMainView, Framework.Net.Settings.TabKeys) Then
                        Return -1
                    End If
                End If
                If Framework.Net.Settings.RSAProvider Is Nothing Then Framework.Net.Settings.SetupRSAProvider()
                If Framework.Net.Settings.UniqueId Is Nothing Then Framework.Net.Settings.SetupUniqueId()

                ''setup security
                Framework.Security.Manager.SetupSystemGroups()

                'in the next segment, worker threads are started. Make sure FMain is already initialized before this segment
                Framework.Net.Manager.Start()

                'make sure todo is loaded before any other plugin since it might be
                'needed by the plugins
                Dim clsToDo As New ToDo.PlugIn
                Host.AddPlugin(clsToDo)

                '' Backup
                Dim clsBackup As New Backup.PlugIn
                Host.AddPlugin(clsBackup)

                '' Initialize Shared Files
                Dim clsFileShare As New FileShare.UI.PlugIn
                Host.AddPlugin(clsFileShare)

                clsMainView.tcPlugs.SelectedIndex = 0
                clsMainView.Enabled = True
            End Using
            Application.Run(clsMainView)
            Return 0
        Catch ex As Exception
            Framework.Misc.HandleException(ex)
            Return -1
        Finally
            Using clsMessage As New Framework.Message
                Host.Stop(clsMessage)
                Framework.Net.Manager.Stop(clsMessage)
            End Using
        End Try
    End Function

    Private Shared Sub UnhandledExceptionHandler_Thread(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
        Try
            MessageBox.Show(e.Exception.Message & vbNewLine & vbNewLine & e.Exception.StackTrace, e.Exception.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbNewLine & vbNewLine & ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub
    Private Shared Sub UnhandledExceptionHandler_Domain(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)
        Try
            Dim clsEx As Exception = CType(e.ExceptionObject, Exception)
            MessageBox.Show(clsEx.Message & vbNewLine & vbNewLine & clsEx.StackTrace, clsEx.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbNewLine & vbNewLine & ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Shared Sub ReadCommandLine(ByVal args() As String)
        Dim strDBPath As String = Nothing
        Dim strDBPwd As String = Nothing

        For Each strArg As String In args
            Dim iPos As Integer = strArg.IndexOf("="c)
            If iPos > 0 Then
                Dim strKey As String = strArg.Substring(0, iPos).ToUpper
                Dim strVal As String = strArg.Substring(iPos + 1)
                Select Case strKey
                    Case "DBPATH", "DBFILE"
                        strDBPath = strVal
                    Case "DBPASSWORD", "DBPWD"
                        strDBPwd = strVal
                End Select
            End If
        Next

        If Not String.IsNullOrEmpty(strDBPath) AndAlso Not String.IsNullOrEmpty(strDBPwd) Then
            Framework.Data.Environment.SetActiveDatabase(strDBPath, strDBPwd)
            mSkipIsoSettings = True
        End If
    End Sub
    Private Shared mSkipIsoSettings As Boolean = False
    Private Shared Function ReadIsoStorageSettings() As Boolean
        If Not mSkipIsoSettings AndAlso IsoDBSettings.Load Then
            If Not String.IsNullOrEmpty(IsoDBSettings.DBPath) AndAlso Not String.IsNullOrEmpty(IsoDBSettings.DBPass) Then
                Framework.Data.Environment.SetActiveDatabase(IsoDBSettings.DBPath, IsoDBSettings.DBPass)
                Return True
            End If
        End If
        Return False
    End Function

End Class


